package cc.cix.gt.org.controller;

import cc.cix.gt.common.constant.StringConstant;
import cc.cix.gt.common.entity.ResultPage;
import cc.cix.gt.common.entity.Tree;
import cc.cix.gt.org.dto.query.QueryMenuReq;
import cc.cix.gt.org.dto.request.MenuReq;
import cc.cix.gt.org.dto.response.PermissionCodeResp;
import cc.cix.gt.org.entity.Menu;
import cc.cix.gt.org.service.IMenuService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * @author cix
 */
@Api(tags = "菜单管理")
@Slf4j
@Validated
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/menu")
public class MenuController {

    private final IMenuService menuService;

    @ApiOperation("菜单列表")
    @GetMapping
    public ResultPage<Tree<Menu>> listMenu(QueryMenuReq dto) {
        return menuService.listMenu(dto);
    }

    @ApiOperation("菜单详情")
    @GetMapping("/{id}")
    public Menu getMenu(@PathVariable String id) {
        return menuService.getById(id);
    }

    @ApiOperation("权限码列表")
    @GetMapping("/permissions")
    public PermissionCodeResp listPermissions() {
        return PermissionCodeResp.builder().codes(menuService.listUserPermission()).build();
    }

    @ApiOperation("添加菜单")
    @PreAuthorize("hasAuthority('menu:add')")
    @PostMapping
    public void addMenu(@Valid @RequestBody MenuReq dto) {
        Menu menu = BeanUtil.toBean(dto, Menu.class);
        menuService.createMenu(menu);
    }

    @ApiOperation("删除菜单")
    @PreAuthorize("hasAuthority('menu:delete')")
    @DeleteMapping("/{menuIds}")
    public void deleteMenus(@PathVariable String menuIds) {
        menuService.deleteMenuByIds(StrUtil.splitTrim(menuIds, StringConstant.COMMA));
    }

    @ApiOperation("更新菜单")
    @PreAuthorize("hasAuthority('menu:update')")
    @PutMapping
    public void updateMenu(@Valid @RequestBody MenuReq dto) {
        Menu menu = BeanUtil.toBean(dto, Menu.class);
        menuService.updateMenu(menu);
    }

}
